package com.symaster.backups.frame.dialog;

import com.symaster.backups.frame.MainFrame;
import com.symaster.backups.frame.element.border.RoundBorder;
import com.symaster.backups.frame.element.layout.TileLayout;
import com.symaster.backups.util.ComponentUtil;
import com.symaster.common.swing.util.SwingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;

/**
 * @author yinmiao
 * @version 2024/2/6
 */
@Component
public class PopupMenuDialog extends JDialog {

    private final Panel root = new Panel();

    @Autowired
    public PopupMenuDialog(ApplicationContext applicationContext, MainFrame mainFrame) {

        this.setTitle("文件自动备份系统");
        this.setContentPane(root);
        this.setUndecorated(true);
        this.setBackground(new Color(0, 0, 0, 0));
        this.addWindowFocusListener(new WindowAdapter() {
            @Override
            public void windowLostFocus(WindowEvent e) {
                dispose();
            }
        });

        root.setBorder(new RoundBorder(new Color(165, 165, 165)));
        root.setLayout(new TileLayout());
        root.setOpaque(false);

        JLabel jLabel = new JLabel("文件自动备份系统");
        jLabel.setBorder(new EmptyBorder(5, 15, 5, 15));
        root.add(jLabel);

        root.add(ComponentUtil.separatorPanel());

        JButton jButton2 = new JButton("显示界面");
        jButton2.setBorder(new EmptyBorder(3, 15, 3, 15));
        jButton2.addActionListener(e -> mainFrame.open());
        root.add(jButton2);

        JButton jButton = new JButton("暂停备份");
        jButton.setBorder(new EmptyBorder(3, 15, 3, 15));
        root.add(jButton);

        JButton jButton1 = new JButton("退出系统");
        jButton1.setBorder(new EmptyBorder(3, 15, 3, 15));
        jButton1.addActionListener(e -> {
            SpringApplication.exit(applicationContext);
            System.exit(0);
        });
        root.add(jButton1);
    }

    public void open(Point locationOnScreen) {
        Dimension preferredSize = root.getPreferredSize();

        pack();
        setBounds(locationOnScreen.x - preferredSize.width, locationOnScreen.y - preferredSize.height, preferredSize.width, preferredSize.height);
        setVisible(true);
    }

    private static final class Panel extends JComponent {

        @Override
        public void paint(Graphics g) {
            SwingUtil.antialiasingOn((Graphics2D) g);

            g.setColor(new Color(255, 255, 255));
            g.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);

            super.paint(g);
        }
    }
}
